﻿using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    public class GenerateVersionTask : Task
    {
        [Output]
        public int Version { get; set; }

        public override bool Execute()
        {
            // 生成版本号的逻辑
            Version = GetVisitCount();
            return true;
        }
        private const string DataFilePath = "visit_counter.dat";

        public static int GetVisitCount()
        {
            // 读取存储的数据
            int visitCount = 0; DateTime lastVisitDate = DateTime.Now;
            ReadData(ref visitCount, ref lastVisitDate);

            // 获取当前日期
            DateTime today = DateTime.Today;

            // 检查是否是新的一天
            if (lastVisitDate < today)
            {
                // 重置访问次数
                visitCount = 0;
                lastVisitDate = today;
            }

            // 增加访问次数
            visitCount++;

            // 保存数据
            SaveData(visitCount, lastVisitDate);

            // 返回访问次数
            return visitCount;
        }

        private static void ReadData(ref int count, ref DateTime countdate)
        {
            if (File.Exists(DataFilePath))
            {
                string[] lines = File.ReadAllLines(DataFilePath);
                if (lines.Length == 2)
                {
                    int visitCount = int.Parse(lines[0]);
                    DateTime lastVisitDate = DateTime.Parse(lines[1]);
                    count = visitCount; countdate = lastVisitDate;
                }
            }
            else
            {
                File.Create(DataFilePath);
                count = 0; countdate = DateTime.Now;
            }
        }

        private static void SaveData(int visitCount, DateTime lastVisitDate)
        {
            string[] lines = { visitCount.ToString(), lastVisitDate.ToString() };
            File.WriteAllLines(DataFilePath, lines);
        }
    }
}
